import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';

// 添加新的 action
const setUsers = (users) => ({
  type: 'SET_USERS',
  payload: users
});

const List = () => {
  const users = useSelector(state => state.users.users);
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();

  useEffect(() => {
    console.log('List component mounted, count:', count);
    const fetchUsers = async () => {
      try {
        const response = await axios.get('/api/users');
        dispatch(setUsers(response.data));
      } catch (error) {
        console.error('Error fetching users:', error);
      }
    };

    fetchUsers();
  }, [dispatch, count]);

  return (
    <div>
      <h1>用户列表</h1>
      <p>当前计数: {count}</p>
      {users.length === 0 ? (
        <p>加载中...</p>
      ) : (
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name} - {user.email}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default List;
